using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using NerdDinner.Models;

namespace NerdDinner.Controllers
{
    public class DinnersController : Controller
    {
        DinnerRepository repository = new DinnerRepository();
        //
        // GET: /Dinners/

        public ActionResult Index()
        {
            var dinners = repository.FindUpcommingDinners().ToList();
            return View("Index", dinners);
        }

        public ActionResult Details(int id)
        {
            var dinner = repository.GetDinner(id);

            if (dinner == null)
                return View("NotFound");
            else
                return View("Details", dinner);
        }

        //
        //  GET: /Dinners/Edit/2

        public ActionResult Edit(int id)
        {
            Dinner dinner = repository.GetDinner(id);
            return View(dinner);
        }

        //
        //  POST: /Dinners/Edit/2

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit(int id, FormCollection formValues)
        {
            //  Retrieve dinner from repository
            Dinner dinner = repository.GetDinner(id);

            try
            {
                //  Update dinner with form posted values

                //dinner.Title = Request.Form["Title"];
                //dinner.Description = Request.Form["Description"];
                //dinner.EventDate = DateTime.Parse(Request.Form["EventDate"]);
                //dinner.Address= Request.Form["Address"];
                //dinner.Country= Request.Form["Country"];
                //dinner.ContactPhone = Request.Form["ContactPhone"];

                UpdateModel(dinner);

                repository.Save();

                return RedirectToAction("Details", new { id = dinner.DinnerID });
            }
            catch
            {
                foreach (var issue in dinner.GetRuleViolations())
                {
                    ModelState.AddModelError(issue.PropertyName, issue.ErrorMessage);
                }
                return View(dinner);
            }
        }
    }
}
